//
//  YZFControllerManager.m
//  YZMicroStock
//
//  Created by wangminhong on 16/3/21.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMControllerManager.h"
#import "YZMainTabbarController.h"
#import "YZMNavigationController.h"
#import "YZMTutorialViewController.h"
#import "YZMUserService.h"
#import "YZMTradeBasicViewController.h"
#import "YZMyStocksViewController.h"
#import "YZMHomePageViewController.h"
#import "YZMFastPayViewController.h"
#import <UIKit/UIKit.h>

@interface YZMControllerManager ()

@property (nonatomic, copy) NSDictionary *ctrlDict;
@property (nonatomic, strong) UITabBarController *rootTabBarCtrl;
@property (nonatomic, strong) UINavigationController  *presentNavCtrl;


@end

@implementation YZMControllerManager

+ (instancetype)sharedManager
{
    static YZMControllerManager *sInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sInstance = [[self alloc] init];;
    });
    
    return sInstance;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.ctrlDict = YZMViewControllerMap();
    }
    return self;
}

- (UINavigationController *)currentNavationCtroller
{
    if (self.presentNavCtrl) {
        return self.presentNavCtrl;
    }
    else
    {
        return (UINavigationController *)self.rootTabBarCtrl.selectedViewController;
    }
}

#pragma mark -- timer

- (void)startTimerTask{
    
    UIViewController *viewController = YZMCMInstance.currentNavationCtroller.topViewController;
    if ([[viewController class] isSubclassOfClass:NSClassFromString(@"YZMTradeBasicViewController")]) {
        
        YZMTradeBasicViewController *vc = (YZMTradeBasicViewController *)viewController;
        [vc startTimer];
        
    }else if([[viewController class] isSubclassOfClass:NSClassFromString(@"YZMyStocksViewController")]){
        
        YZMyStocksViewController *vc = (YZMyStocksViewController *)viewController;
        [vc startTimer];
    }else if([[viewController class] isSubclassOfClass:NSClassFromString(@"YZMHomePageViewController")]){
        
        YZMHomePageViewController *vc = (YZMHomePageViewController *)viewController;
        [vc startTimer];
    }
}

- (void)stopTimerTask{
    
    UIViewController *viewController = YZMCMInstance.currentNavationCtroller.topViewController;
    if ([[viewController class] isSubclassOfClass:NSClassFromString(@"YZMTradeBasicViewController")]) {
        
        YZMTradeBasicViewController *vc = (YZMTradeBasicViewController *)viewController;
        [vc stopTimer];
    }else if([[viewController class] isSubclassOfClass:NSClassFromString(@"YZMyStocksViewController")]){
        
        YZMyStocksViewController *vc = (YZMyStocksViewController *)viewController;
        [vc stopTimer];
    }else if([[viewController class] isSubclassOfClass:NSClassFromString(@"YZMHomePageViewController")]){
        
        YZMHomePageViewController *vc = (YZMHomePageViewController *)viewController;
        [vc stopTimer];
    }
}

//wangmh remark 快捷支付跳转到外部浏览器
//- (void)rechargeCheckTask{
//    
//    UIViewController *viewController = YZMCMInstance.currentNavationCtroller.topViewController;
//    if ([[viewController class] isSubclassOfClass:NSClassFromString(@"YZMFastPayViewController")]) {
//        
//        YZMFastPayViewController *vc = (YZMFastPayViewController *)viewController;
//        [vc checkIfRechargeFinished];
//    }
//}

#pragma mark -

- (Class)classForControllerName: (NSString *)ctrlName
{
    NSString *ctrlClassName = self.ctrlDict[ctrlName];
    Class ctrlClass = NSClassFromString(ctrlClassName);
    if (ctrlClass == nil) {
        ctrlClass = NSClassFromString(ctrlName);
    }
    return ctrlClass;
}

#pragma mark - viewController rooting

#pragma mark - fixed rooting

- (void)tabRoot
{
    UINavigationController *navCtrl = self.rootTabBarCtrl.viewControllers[self.rootTabBarCtrl.selectedIndex];
    [navCtrl popToRootViewControllerAnimated: YES];
}

- (void)tabRootAtIndex: (NSInteger)index
{
    self.rootTabBarCtrl.selectedIndex = index;
    [self tabRoot];
}

- (void)home
{
    [self tabRootAtIndex: 0];
}

- (void)accountRoot
{
    [self tabRootAtIndex: 4];
}

-(void)discivery{
    [self tabRootAtIndex:3];
}

- (void)back
{
    UINavigationController *navCtrl = self.rootTabBarCtrl.viewControllers[self.rootTabBarCtrl.selectedIndex];
    if (navCtrl.viewControllers.count > 1) {
        [navCtrl popToRootViewControllerAnimated: YES];
    }
}

- (BOOL)fixedRootingForName: (NSString *)fixedName
{
    if ([fixedName isEqualToString: YZHomeCtlr]) {
        [self home];
        return YES;
    }
    else if ([fixedName isEqualToString: YZTabRootCtrl])
    {
        [self tabRoot];
        return YES;
    }
    else if ([fixedName isEqualToString: YZAccountCtrl])
    {
        [self accountRoot];
        return YES;
    }
    else if ([fixedName isEqualToString: YZBackCtrl])
    {
        [self back];
        return YES;
    }else if([fixedName isEqualToString: YZDiscoveryCtrl]){
        [self discivery];
        return YES;
    }
    return NO;
}

#pragma mark - ctrl modify

- (void)pushAfterRootController: (id)controller atIndex: (NSInteger)index animated:(BOOL)animated{
    
    self.rootTabBarCtrl.selectedIndex = index;
    UINavigationController *navCtrl = self.rootTabBarCtrl.viewControllers[self.rootTabBarCtrl.selectedIndex];
    if (navCtrl == nil) {
        return;
    }
    UIViewController *rootCtrl = navCtrl.viewControllers[0];
    [navCtrl setViewControllers: @[rootCtrl, controller] animated: animated];
}

- (void)pushAfterRootController: (id)controller atIndex: (NSInteger)index
{
    self.rootTabBarCtrl.selectedIndex = index;
    UINavigationController *navCtrl = self.rootTabBarCtrl.viewControllers[self.rootTabBarCtrl.selectedIndex];
    if (navCtrl == nil) {
        return;
    }
    UIViewController *rootCtrl = navCtrl.viewControllers[0];
    [navCtrl setViewControllers: @[rootCtrl, controller] animated: YES];
}

- (void)pushControllersAfterRootController: (NSArray *)controllers atIndex: (NSInteger)index
{
    self.rootTabBarCtrl.selectedIndex = index;
    UINavigationController *navCtrl = self.rootTabBarCtrl.viewControllers[self.rootTabBarCtrl.selectedIndex];
    if (navCtrl == nil) {
        return;
    }
    UIViewController *rootCtrl = navCtrl.viewControllers[0];
    NSArray *array = [@[rootCtrl] arrayByAddingObjectsFromArray: controllers];
    [navCtrl setViewControllers: array animated: YES];
}

- (void)pushAfterRootWithName: (NSString *)name andParams: (NSDictionary *)params atIndex: (NSInteger)index
{
    id ctrl = [self viewControllerForName: name withParams: params];
    [self pushAfterRootController: ctrl atIndex: index];
}

- (void)setAfterRootWithName: (NSString *)name andParams: (NSDictionary *)params atIndex: (NSInteger)index
{
    id ctrl = [self viewControllerForName: name withParams: params];
    [self pushAfterRootController: ctrl atIndex: index animated:NO];
}

- (void)pushAfterRootWithNames: (NSArray *)names andParams: (NSArray *)paramArray atIndex: (NSInteger)index
{
    NSMutableArray *array = [NSMutableArray array];
    for (NSInteger i = 0; i < names.count; i++) {
        NSString *name = [names objectAtIndex: i];
        NSDictionary *params = nil;
        if (i < paramArray.count) {
            params = paramArray[i];
            if ([params isKindOfClass: [NSNull class]]) {
                params = nil;
            }
        }
        id ctrl = [self viewControllerForName: name withParams: params];
        [array addObject: ctrl];
    }
    
    [self pushControllersAfterRootController: array atIndex: index];
}

- (void)pushViewController:(id)ctrl animated:(BOOL)animated
{
    if (self.presentNavCtrl) {
        [self.presentNavCtrl pushViewController: ctrl animated: animated];
    }
    else
    {
        UINavigationController *navCtrl = (UINavigationController *)self.rootTabBarCtrl.selectedViewController;
        [navCtrl pushViewController: ctrl animated: YES];
    }
}

- (void)pushViewController: (id)ctrl
{
    [self pushViewController: ctrl animated: YES];
}

- (void)popViewController: (id)ctrl animated: (BOOL)animated
{
    UINavigationController *navCtrl = nil;
    if (self.presentNavCtrl) {
        navCtrl = self.presentNavCtrl;
    }
    else
    {
        navCtrl = self.rootTabBarCtrl.viewControllers[self.rootTabBarCtrl.selectedIndex];
    }
    if (ctrl == nil) {
        [navCtrl popViewControllerAnimated: animated];
    }
    else
    {
        [navCtrl popToViewController: ctrl animated: animated];
    }
}

- (void)popViewController: (id)ctrl
{
    [self popViewController: ctrl animated: YES];
}

- (void)popViewToRootControllerAnimated: (BOOL)animated
{
    UINavigationController *navCtrl = self.rootTabBarCtrl.viewControllers[self.rootTabBarCtrl.selectedIndex];
    [navCtrl popToRootViewControllerAnimated: animated];
}

- (void)silentPopToRootViewControllerAtIndex: (NSInteger)index
{
    UINavigationController *navCtrl = self.rootTabBarCtrl.viewControllers[index];
    UIViewController *root = navCtrl.viewControllers[0];
    [navCtrl setViewControllers: @[root]];
}

- (void)popViewControllerAnimated: (BOOL)animated
{
    if (self.presentNavCtrl) {
        [self.presentNavCtrl popViewControllerAnimated: animated];
    }
    else
    {
        [(UINavigationController *)self.rootTabBarCtrl.selectedViewController popViewControllerAnimated: animated];
    }
}

- (void)popViewController
{
    [self popViewControllerAnimated: YES];
}

- (void)clearControllerAtTabIndex: (NSInteger)index
{
    UINavigationController *navCtrl = self.rootTabBarCtrl.viewControllers[self.rootTabBarCtrl.selectedIndex];
    [navCtrl popToRootViewControllerAnimated: NO];
}

#pragma mark - instance op

- (void)pushViewController: (id)ctrl atIndex: (NSInteger)index
{
    self.rootTabBarCtrl.selectedIndex = index;
    [self pushViewController: ctrl];
}

- (void)popViewController: (id)ctrl atIndex: (NSInteger)index
{
    self.rootTabBarCtrl.selectedIndex = index;
    [self popViewController: ctrl];
}

- (void)presentViewController: (id)ctrl
{
    void (^presentBlock)(void) = ^(){
        self.presentNavCtrl = ctrl;
        [self.rootTabBarCtrl presentViewController: ctrl animated: NO completion: nil];
    };
    
    if (self.presentNavCtrl != nil) {
        [self.rootTabBarCtrl dismissViewControllerAnimated: NO completion: presentBlock];
    }
    else
    {
        presentBlock();
    }
}

- (void)dismissViewControllerComplete: (void(^)())complete
{
    if (self.presentNavCtrl) {
        [self.rootTabBarCtrl dismissViewControllerAnimated: YES completion: complete];
        self.presentNavCtrl = nil;
        
        //LOCK View 消失后，判断是否是充值的页面
        //wangmh remark 快捷支付跳转到外部浏览器
//        [self rechargeCheckTask];
    }
}

- (void)dismissViewController
{
    [self dismissViewControllerComplete: nil];
}

- (id)substanceWithClassName: (Class)ctrlClass
{
    if (ctrlClass) {
        UINavigationController *navCtrl = self.rootTabBarCtrl.viewControllers[self.rootTabBarCtrl.selectedIndex];
        UIViewController *foundCtrl = nil;
        for (UIViewController *current in navCtrl.viewControllers) {
            if ([current.class isSubclassOfClass: ctrlClass]) {
                foundCtrl = current;
                break;
            }
        }
        return foundCtrl;
    }
    return nil;
}

- (id)instanceWithClassName: (Class)ctrlClass
{
    if (ctrlClass) {
        UINavigationController *navCtrl = self.rootTabBarCtrl.viewControllers[self.rootTabBarCtrl.selectedIndex];
        UIViewController *foundCtrl = nil;
        for (UIViewController *current in navCtrl.viewControllers) {
            if (current.class == ctrlClass) {
                foundCtrl = current;
                break;
            }
        }
        return foundCtrl;
    }
    return nil;
}

- (id)instanceBeforeClassName: (Class)ctrlClass
{
    id foundCtrl = [self instanceWithClassName:ctrlClass];
    
    if (foundCtrl) {
        
        UINavigationController *navCtrl = self.rootTabBarCtrl.viewControllers[self.rootTabBarCtrl.selectedIndex];
        NSInteger index = [navCtrl.viewControllers indexOfObject:foundCtrl];
        
        if (index > 0) {
            
            return [navCtrl.viewControllers objectAtIndex:index-1];
        }
        
        return nil;
    }
    
    return nil;
}

- (id)substanceWithControllerName: (NSString *)name
{
    Class ctrlClass = [self classForControllerName: name];
    return [self substanceWithClassName: ctrlClass];
}

- (id)instanceWithControllerName: (NSString *)name
{
    if ([name isEqualToString:@"stock"] || [name isEqualToString:@"stockTD"]) {
        name = @"stockTotal";
    }
    Class ctrlClass = [self classForControllerName: name];
    return [self instanceWithClassName: ctrlClass];
}

- (void)popViewControllerToClass: (Class)ctrlClass animated: (BOOL)animated
{
    id foundCtrl = [self instanceWithClassName: ctrlClass];
    if (foundCtrl) {
        UINavigationController *navCtrl = self.rootTabBarCtrl.viewControllers[self.rootTabBarCtrl.selectedIndex];
        [navCtrl popToViewController: foundCtrl animated: animated];
    }
}

- (void)popViewControllerToControllerName: (NSString *)ctrlName animated: (BOOL)animated
{
    Class ctrlClass = [self classForControllerName: ctrlName];
    [self popViewControllerToClass: ctrlClass animated: animated];
}

- (void)popViewControllerBeforeClass: (Class)ctrlClass animated:(BOOL)animated{
    
    id foundCtrl = [self instanceBeforeClassName:ctrlClass];
    if (foundCtrl) {
        UINavigationController *navCtrl = self.rootTabBarCtrl.viewControllers[self.rootTabBarCtrl.selectedIndex];
        [navCtrl popToViewController: foundCtrl animated: animated];
    }
}

- (void)popViewControllerBeforeControllerName:(NSString *)ctrlName animated:(BOOL)animated{
    
    Class ctrlClass = [self classForControllerName:ctrlName];
    [self popViewControllerBeforeClass:ctrlClass animated:animated];
}

#pragma mark - name op

- (void)pushViewControllerWithName: (NSString *)name andParams: (NSDictionary *)params
{
    if ([self fixedRootingForName: name]) {
        return;
    }
    UIViewController *ctrl = [self viewControllerForName: name withParams: params];
    if (ctrl) {
        [self pushViewController: ctrl];
    }
}

- (void)popToRootViewControllerAnimated: (BOOL)animated
{
    if (self.presentNavCtrl) {
        [self.presentNavCtrl popToRootViewControllerAnimated: animated];
    }
    else
    {
        [(UINavigationController *)self.rootTabBarCtrl.selectedViewController popToRootViewControllerAnimated: animated];
    }
}

- (void)popToRootViewController
{
    [self popToRootViewControllerAnimated: YES];
}

- (void)pushViewControllerWithName: (NSString *)name andParams: (NSDictionary *)params atIndex: (NSInteger)index
{
    UIViewController *ctrl = [self viewControllerForName: name withParams: params];
    if (ctrl) {
        [self pushViewController: ctrl atIndex: index];
    }
}

- (void)pushAfterRootWithNameAndParams: (NSArray *)nameAndParams animated: (BOOL) animated
{
    NSMutableArray *tempArray = [NSMutableArray array];
    UINavigationController *currentNav = self.currentNavationCtroller;
    [tempArray addObject: currentNav.viewControllers[0]];
    for (NSArray *array in nameAndParams) {
        if (array.count == 0) {
            return;
        }
        NSString *name = array[0];
        NSDictionary *params = nil;
        if (array.count >1) {
            params = array[1];
        }
        UIViewController *ctrl = [self viewControllerForName: name withParams: params];
        if (ctrl) {
            [tempArray addObject: ctrl];
        }
    }
    [currentNav setViewControllers: tempArray animated: animated];
}

- (void)pushAfterRootWithNameAndParams: (NSArray *)nameAndParams
{
    [self pushAfterRootWithNameAndParams: nameAndParams animated: YES];
}

- (void)pushAfterName: (NSString *)frontName withControllerName:(NSString *)name andParams: (NSDictionary *)params
{
    Class cls = [self classForControllerName: frontName];
    if (cls == nil) {
        return;
    }
    UINavigationController *navCtrl = self.currentNavationCtroller;
    UIViewController *target = nil;
    for (UIViewController *ctrl in navCtrl.viewControllers) {
        if ([ctrl isKindOfClass: cls]) {
            target = ctrl;
            break;
        }
    }
    
    if (target) {
        [self pushAfterTarget: target withControllerName: name andParams: params];
    }
}

- (void)pushBeforeName: (NSString *)frontName withControllerName:(NSString *)name andParams: (NSDictionary *)params
{
    Class cls = [self classForControllerName: frontName];
    if (cls == nil) {
        return;
    }
    UINavigationController *navCtrl = self.currentNavationCtroller;
    UIViewController *target = nil;
    for (UIViewController *ctrl in navCtrl.viewControllers) {
        if ([ctrl isKindOfClass: cls]) {
            target = ctrl;
            break;
        }
    }
    
    if (target) {
        [self pushAfterTarget: target withControllerName: name andParams: params];
    }
}


- (void)pushAfterTarget: (id)front withControllerName:(NSString *)name andParams: (NSDictionary *)params
{
    UINavigationController *navCtrl = self.currentNavationCtroller;
    NSInteger index = [navCtrl.viewControllers indexOfObject: front];
    if (index != NSNotFound) {
        NSMutableArray *tempArray = [navCtrl.viewControllers subarrayWithRange: NSMakeRange(0, index)].mutableCopy;
        if (tempArray.count > 0) {
            UIViewController *ctrl = [self viewControllerForName: name withParams: params];
            if (ctrl) {
                [tempArray addObject: ctrl];
            }
            [navCtrl setViewControllers: tempArray animated: YES];
        }
    }
}

- (void)presentViewControllerWithName: (NSString *)name andParams: (NSDictionary *)params
{
    UIViewController *ctrl = [self viewControllerForName: name withParams: params];
    
    if (ctrl) {
        UINavigationController *navCtrl = [[YZMNavigationController alloc] initWithRootViewController: ctrl];
        [self presentViewController: navCtrl];
    }
}

#pragma mark - factory

- (UIViewController *)viewControllerForName: (NSString *)name withParams: (NSDictionary *)params
{
     NSMutableDictionary *param = [NSMutableDictionary dictionaryWithDictionary:params];
    if ([name isEqualToString:@"stock"] || [name isEqualToString:@"stockTD"]) {
        if ([name isEqualToString:@"stockTD"]) {
            if (param != nil) {
                param[scrollIndexTotalTD] = @1;
            }
        }
        name = @"stockTotal";
    }
    Class ctrlClass = [self classForControllerName: name];
    if (ctrlClass == nil) {
        return nil;
    }
    
    UIViewController *controller = nil;
    if ([(NSObject *)ctrlClass respondsToSelector: @selector(createWithParams:)]) {
        controller = [ctrlClass createWithParams: param];
    }
    else
    {
        controller = [[ctrlClass alloc] init];
    }
    return controller;
}


#pragma mark - first page

- (void)setupBtNibObject: (YZMainTabBarController *)ctrl
{
    if (self.rootTabBarCtrl == nil) {
        self.rootTabBarCtrl = ctrl;
    }
}

/*进入新手教程*/
- (void)moveToTutorial{
    
    YZMTutorialViewController *viewController = [[YZMTutorialViewController alloc] init];
    viewController.view.tag = 1;
    UIWindow *keyWindow = [[UIApplication sharedApplication].delegate window];
    keyWindow.rootViewController = viewController;
    
    [keyWindow makeKeyAndVisible];
}

/*进入主页面*/
- (void)moveToMain
{
//    if (self.rootTabBarCtrl == nil) {
        YZMainTabBarController *mainVC = [[YZMainTabBarController alloc] init];
        self.rootTabBarCtrl = mainVC;
//    }
    [[UIApplication sharedApplication] setStatusBarHidden:FALSE];
    UIWindow *keyWindow = [[UIApplication sharedApplication].delegate window];
    keyWindow.rootViewController = self.rootTabBarCtrl;
}

+ (void)initAndEnter
{
    YZMControllerManager *manager = [YZMControllerManager sharedManager];
    /*判断是否首次进入程序*/
    if (![[NSUserDefaults standardUserDefaults] boolForKey:sYZMUnShowGuidePageFlagDefault]) {
        if (!YZMSWitchOn) {
            [manager moveToMain];
        }else{
            [manager moveToTutorial];
        }
    }
    else
    {
        NSString *string = [[NSUserDefaults standardUserDefaults] objectForKey:sYZMAppCurrentBuildVersionDefault];
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        
        if ([string isEqualToString:[infoDictionary objectForKey:@"CFBundleVersion"]]) {
            
            /*进入主页面*/
            [manager moveToMain];
            
        }else{
            
            /*版本升级*/
            if (!YZMSWitchOn) {
                [manager moveToMain];
            }else{
                [manager moveToTutorial];
            }
        }
    }
}

- (void)pushByCheckingAuthWithName:(NSString *)name andParams:(NSDictionary *)params
{
    [YZMUserService pushByCheckingAuthWithName: name andParams: params];
}

@end
